package com.fare.taluo.core.domain.crawl.adapter.sub;


import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.fare.taluo.conf.ConfigContainer;
import com.fare.taluo.conf.system.DefaultPropertiesLoader;
import com.fare.taluo.core.domain.crawl.CrawlCSAirLineModel;
import com.fare.taluo.core.domain.crawl.adapter.AbstractAdapter;
import com.fare.taluo.db.hbase.HBasePropertiesLoader;
import com.fare.taluo.vo.core.FlightInfoVO;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlRadioButtonInput;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;

/**
 * 
 * 厦门航空航线的验证保存适配器
 * 
 * */
public class MFAirLineAdaptor extends AbstractAdapter {
	private WebClient webClient=null;
	
	public final static String URL="http://www.xiamenair.com/cn/cn/traveler/flightschedule.aspx";
	
	public MFAirLineAdaptor(CrawlCSAirLineModel portModel) {
		super(portModel);
		
	}
	
	public List<Object> fetch(String url) throws Exception {
		String flightNo=null;
		String fromCityName=null;
		String toCityName=null;
		String frequence=null;//班期
		String stopCityName=null;//经停城市
		String stopArriveTime=null;//经停到达时间
		String stopDepartTime=null;//经停出发时间
		String departTime=null;//出发时间
		String arriveTime=null;//到达时间
		String effectTime=null;//有效日期
		HtmlPage result=null;
		List<Object> finalResult=null;
		FlightInfoVO entityVo = new FlightInfoVO();
		
		
//		webClient =new WebClient(BrowserVersion.CHROME_16);
		webClient=super.getWebClient();//对ajax支持比较好
		webClient.setThrowExceptionOnScriptError(false);
		webClient.setThrowExceptionOnFailingStatusCode(false);
		webClient.setJavaScriptEnabled(true);
		webClient.setRedirectEnabled(true);
		webClient.setCssEnabled(false);
		webClient.setActiveXNative(true);
		HtmlForm form =null;
		try{
			
			HtmlPage rootPage=webClient.getPage(URL);
//			form=(HtmlForm)rootPage.getElementByName("aspnetForm");
			form=(HtmlForm)rootPage.getElementsByName("aspnetForm").get(0);
			HtmlSelect fromCity=form.getElementById("ctl00_ContentPlaceHolder1_ddldomestic");
			HtmlSelect toCity  =  form.getElementById("ctl00_ContentPlaceHolder1_ddlendcity");
			HtmlRadioButtonInput local=form.getElementById("ctl00_ContentPlaceHolder1_r1");//国内航线
			Thread.sleep(3000);
			local.setChecked(true);
		
			if(fromCity.getOptionByValue(this.portModel.getFromCity()) != null  ){
				/*
				 * 下面一系列的点击按钮是模拟网页点击选择航线，由于速度太快（单击变双击），数据传输出错，所以让点击间隔开
				*/
				
				
				fromCity.click();
				Thread.sleep(1000);
				fromCity.click();
				Thread.sleep(1000);
				fromCity.setSelectedAttribute(this.portModel.getFromCity(), true);
				fromCity.click();
				Thread.sleep(2000);
				
				int toCityAllsizes=toCity.getOptionSize();
				if(toCityAllsizes>0){
				for(int k=0;k<toCityAllsizes;k++){
					
					toCity.getOption(k);
					System.out.println("航线="+this.portModel.getFromCity()+"-"+toCity.getOption(k));
					toCity.setSelectedAttribute(toCity.getOption(k), true);
					
					Thread.sleep(3000);
					result=form.getElementById("ctl00_ContentPlaceHolder1_btnsearch").click();
					//解析数据
					if(result!=null){
						Document doc=Jsoup.parse(result.asXml());
						Elements trs=doc.getElementsByAttributeValue("class","odd").tagName("tr");
						int trSizes=trs.size();
						if(trSizes>0){
							finalResult=new ArrayList<Object>();
							result.remove();
							for(int i=0;i<trSizes;i++){
								org.jsoup.nodes.Element tds=trs.get(i).tagName("td");
								flightNo=tds.child(0).html();
								frequence=tds.child(1).html();
								fromCityName=tds.child(2).html();
								departTime=tds.child(3).html();
								if(tds.child(4).html() !=null  && tds.child(4).html().length()>0){
									stopCityName=tds.child(4).html();
									stopArriveTime=tds.child(5).html();
									stopDepartTime=tds.child(6).html();
								}
								toCityName=tds.child(7).html();
								arriveTime=tds.child(8).html();
								effectTime=tds.child(11).html();
								String[] effiectTimeString=effectTime.split("至");
								String effectStartTime=effiectTimeString[0].trim();
								String effectEndTime=effiectTimeString[1].trim();
								entityVo.setFlightNo(flightNo);
								entityVo.setFrequence(frequence);
								entityVo.setFromCityName(fromCityName);
								if(stopCityName !=null &&  stopCityName.length()>0){
									entityVo.setStopCity(stopCityName);
								}
								entityVo.setToCityName(toCityName);
								entityVo.setFlightStartTime(departTime);
								entityVo.setFlightEndTime(arriveTime);
								entityVo.setEffectStartTime(effectStartTime);
								entityVo.setEffectEndTime(effectEndTime);
								finalResult.add(entityVo);
							}
						}
						
					}
				}
			}
				/*if(toCity.getOptionByValue(this.portModel.getToCity()) !=null   ){
					toCity.setSelectedAttribute(toCity.getOptionByValue(this.portModel.getToCity()),true,true);
				}*/
				
				
				
				
			}
				
		}catch (Exception e) {
			clearWeb();
//			throw e;
			throw new Exception("没有该航线");
		}
		return finalResult;
//		return result;
	}
	private void clearWeb(){
		try{
			if(webClient!=null){
				webClient.closeAllWindows();
				webClient=null;
			}
		}catch(Exception e){}
	}

		public static void main(String[] args) {
			//加载配置文件
			//系统默认的config.properties配置文件
			ConfigContainer.getInstance().register(DefaultPropertiesLoader.class);
			//hbase数据库配置文件(可以改为像jdbc.properties文件一样由spring加载)
			ConfigContainer.getInstance().register(HBasePropertiesLoader.class);
			//抓取数据相关配置
			ConfigContainer.getInstance().register("com.fare.taluo.core.domain.crawl.CrawlPropertiesLoader");
			CrawlCSAirLineModel portModel = new CrawlCSAirLineModel();
			portModel.setFromCity("PEK");
			portModel.setToCity("JJN");
			MFAirLineAdaptor adap = new MFAirLineAdaptor(portModel);
			try {
				Object obj = adap.fetch(null);
				System.out.println("obj=="+obj.toString());
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
	


	@Override
	public List<Object> paraseToVo(Object fetchObject) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public String getUrl() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public boolean validateFetch(Object fetchObject) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}
	
	

}
